package com.tigger.core.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * Created by root on 2018/7/21.
 */
public class RedissonDistributedRLocker implements DistributedRLocker {

    private RedissonClient redissonClient;

    @Override
    public boolean lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if(!lock.isLocked()) {
            lock.lock();
            return lock.isLocked();
        }
        return false;
    }

    @Override
    public boolean lock(String lockKey, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        if(!lock.isLocked()) {
            lock.lock(timeout, TimeUnit.SECONDS);
            return lock.isLocked();
        }
        return false;
    }

    @Override
    public boolean lock(String lockKey, TimeUnit unit, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        if(!lock.isLocked()) {
            lock.lock(timeout, unit);
            return lock.isLocked();
        }
        return false;
    }

    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            if (!lock.isLocked()) {
                return lock.tryLock(waitTime, leaseTime, unit);
            }
            return false;
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    @Override
    public void unlock(RLock lock) {
        lock.unlock();
    }

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }
}
